import { useState, useCallback, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { MessageCircle, X, Send, Cat, Lightbulb, CheckCircle, AlertTriangle } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

interface MirrorAgentProps {
  nodes: any[];
  edges: any[];
}

interface Suggestion {
  id: string;
  type: 'tip' | 'warning' | 'success';
  message: string;
  action?: string;
}

export function MirrorAgent({ nodes, edges }: MirrorAgentProps) {
  const [isExpanded, setIsExpanded] = useState(false);
  const [message, setMessage] = useState('');
  const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
  const { toast } = useToast();

  // Analyze canvas state and generate suggestions
  const analyzeCanvas = useCallback(() => {
    const newSuggestions: Suggestion[] = [];
    
    // Check for unconnected nodes
    const connectedNodeIds = new Set([
      ...edges.map(e => e.source),
      ...edges.map(e => e.target)
    ]);
    const unconnectedNodes = nodes.filter(node => !connectedNodeIds.has(node.id));
    
    if (unconnectedNodes.length > 0) {
      newSuggestions.push({
        id: 'unconnected',
        type: 'warning',
        message: `${unconnectedNodes.length} unconnected module${unconnectedNodes.length > 1 ? 's' : ''}. Consider linking them to create a flow.`,
        action: 'Connect modules'
      });
    }
    
    // Check for missing descriptions
    const nodesWithoutDescription = nodes.filter(node => 
      !node.data?.description || node.data.description.trim() === ''
    );
    
    if (nodesWithoutDescription.length > 0) {
      newSuggestions.push({
        id: 'descriptions',
        type: 'tip',
        message: `${nodesWithoutDescription.length} module${nodesWithoutDescription.length > 1 ? 's' : ''} could use better descriptions for clarity.`,
        action: 'Add descriptions'
      });
    }
    
    // Check for good practices
    if (nodes.length >= 3 && edges.length >= 2) {
      newSuggestions.push({
        id: 'good-flow',
        type: 'success',
        message: 'Great! Your flow is taking shape. Consider adding interactive elements to engage learners.',
        action: 'Add interaction'
      });
    }
    
    // Check for quiz modules
    const hasQuiz = nodes.some(node => 
      node.type?.includes('quiz') || 
      node.type?.includes('multiple-choice') ||
      node.type?.includes('select-answer')
    );
    
    if (nodes.length > 2 && !hasQuiz) {
      newSuggestions.push({
        id: 'add-quiz',
        type: 'tip',
        message: 'Consider adding a quiz or interactive question to assess learning.',
        action: 'Add quiz'
      });
    }
    
    setSuggestions(newSuggestions);
  }, [nodes, edges]);

  // Re-analyze when canvas changes
  useEffect(() => {
    const timeoutId = setTimeout(analyzeCanvas, 500);
    return () => clearTimeout(timeoutId);
  }, [nodes, edges, analyzeCanvas]);

  const handleSendMessage = () => {
    if (!message.trim()) return;
    
    // Simulate AI response
    toast({
      title: "Mirror Agent",
      description: "Thanks for your question! I'm analyzing your workflow...",
    });
    
    setMessage('');
    
    // Add a contextual suggestion based on the message
    setTimeout(() => {
      setSuggestions(prev => [...prev, {
        id: `response-${Date.now()}`,
        type: 'tip',
        message: "Based on your question, I recommend organizing your modules in a logical learning sequence: Introduction → Content → Practice → Assessment.",
        action: 'Reorganize flow'
      }]);
    }, 1000);
  };

  const getSuggestionIcon = (type: string) => {
    switch (type) {
      case 'success': return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'warning': return <AlertTriangle className="w-4 h-4 text-orange-500" />;
      default: return <Lightbulb className="w-4 h-4 text-blue-500" />;
    }
  };

  return (
    <div className="fixed bottom-6 right-6 z-50">
      {/* Expanded Chat Panel */}
      {isExpanded && (
        <Card className="mb-4 w-80 h-96 flex flex-col bg-white border border-gray-200 shadow-lg animate-scale-in">
          {/* Header */}
          <div className="flex items-center justify-between p-4 border-b border-gray-200">
            <div className="flex items-center gap-2">
              <div className="p-1.5 rounded-full bg-purple-100">
                <Cat className="w-4 h-4 text-purple-600" />
              </div>
              <h3 className="font-semibold text-sm text-gray-900">Mirror Agent</h3>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsExpanded(false)}
              className="h-8 w-8 p-0 hover:bg-gray-100"
            >
              <X className="w-4 h-4" />
            </Button>
          </div>
          
          {/* Suggestions Area */}
          <div className="flex-1 p-4 overflow-y-auto space-y-3">
            {suggestions.length === 0 ? (
              <div className="text-center text-gray-500 text-sm py-8">
                <Cat className="w-8 h-8 mx-auto mb-2 opacity-50 text-gray-400" />
                <p>Your canvas looks great!</p>
                <p>Keep building and I'll share tips.</p>
              </div>
            ) : (
              suggestions.map((suggestion) => (
                <div
                  key={suggestion.id}
                  className="p-3 rounded-lg bg-gray-50 border border-gray-200 animate-fade-in"
                >
                  <div className="flex items-start gap-2">
                    {getSuggestionIcon(suggestion.type)}
                    <div className="flex-1 min-w-0">
                      <p className="text-xs text-gray-900 leading-relaxed">
                        {suggestion.message}
                      </p>
                      {suggestion.action && (
                        <Button
                          variant="outline"
                          size="sm"
                          className="mt-2 h-6 text-xs px-2 hover:scale-105 transition-transform"
                        >
                          {suggestion.action}
                        </Button>
                      )}
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>
          
          {/* Input Area */}
          <div className="p-4 border-t border-gray-200">
            <div className="flex gap-2">
              <Input
                placeholder="Ask me anything..."
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
                className="text-sm h-8"
              />
              <Button
                onClick={handleSendMessage}
                size="sm"
                className="h-8 px-3 hover:scale-105 transition-transform"
                disabled={!message.trim()}
              >
                <Send className="w-3 h-3" />
              </Button>
            </div>
          </div>
        </Card>
      )}
      
      {/* Floating Button */}
      <Button
        onClick={() => setIsExpanded(!isExpanded)}
        className={`rounded-full transition-all duration-300 hover:scale-110 ${
          isExpanded 
            ? 'bg-purple-600 text-white shadow-lg' 
            : 'bg-white text-slate-900 border border-slate-200 hover:bg-slate-50 shadow-md'
        }`}
        size="lg"
      >
        <div className="flex items-center gap-2">
          <div className="p-1 rounded-full bg-purple-100">
            <Cat className="w-4 h-4 text-purple-600" />
          </div>
          {!isExpanded && (
            <span className="text-sm font-medium">Need help?</span>
          )}
          {isExpanded && <MessageCircle className="w-4 h-4" />}
        </div>
        
        {/* Notification Badge */}
        {!isExpanded && suggestions.length > 0 && (
          <div className="absolute -top-1 -right-1 w-5 h-5 bg-purple-600 text-white rounded-full flex items-center justify-center text-xs font-bold animate-pulse">
            {suggestions.length}
          </div>
        )}
      </Button>
    </div>
  );
}